<template>
  <div class="risk-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchUserRiskVisible" inline size="mini" :model="searchUserRiskForm" ref="searchMenuForm" @keyup.enter.native="searchUserRiskHandle">
        <el-form-item prop="userId" label="风控记录检索">
          <el-select v-model="searchUserRiskForm.userId" clearable filterable placeholder="请选择用户" class="user-role">
            <el-option
              v-for="user in userList"
              :key="user.value"
              :label="user.name"
              :value="user.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="riskType">
          <el-select v-model="searchUserRiskForm.riskType" clearable placeholder="请选择风控类型" class="user-role">
            <el-option
              v-for="item in typeEnums"
              :key="'riskType' + item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchUserRiskForm.status" clearable placeholder="请选择风控状态" class="user-role">
            <el-option
              v-for="item in statusEnums"
              :key="'status' + item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker type="date" value-format="timestamp" placeholder="开始日期" v-model="searchUserRiskForm.startCreateTime" class="date-picker"></el-date-picker>
          至
          <el-date-picker type="date" value-format="timestamp" placeholder="结束日期" v-model="searchUserRiskForm.endCreateTime" class="date-picker"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchUserRiskHandle" type="primary"
                     icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetSearchUserRiskFormHandle" plain
                     icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="m-tool">
      <span style="height: 100%;"></span>
      <!-- 还差一个刷新表格事件 -->
      <right-tool-bar :search-visible="searchUserRiskVisible" :search-load="dataLoad"
                      @toggle-search="searchUserRiskVisible = !searchUserRiskVisible" @refresh-table="getUserRiskList" />
    </div>
    <el-table
      v-loading="dataLoad"
      element-loading-text="用户风控数据加载中"
      element-loading-spinner="el-icon-loading"
      :data="userRiskList"
      ref="userRiskTable"
    >
      <el-table-column prop="userName" header-align="center" align="center" label="用户名称"></el-table-column>
      <el-table-column prop="riskType" header-align="center" align="center" label="风控类型">
        <template v-slot="{ row }">
          {{ row.riskType | parseRiskType(typeEnums) }}
        </template>
      </el-table-column>
      <el-table-column prop="riskReason" header-align="center" align="center" label="风控原因">
        <template v-slot="{ row }">
          <span @click="openAuditRiskDialogHandle(row)" class="riskReason" :style="{'--color': themeColor}">
            {{ row.riskReason }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="风控状态">
        <template v-slot="{ row }">
          {{ row.status | parseStatus(statusEnums) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="风控时间" width="135"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="操作用户"></el-table-column>
      <el-table-column prop="updateTime" header-align="center" align="center" label="更新时间" width="135"></el-table-column>
      <el-table-column prop="updateUser" header-align="center" align="center" label="更新用户"></el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
      <el-table-column header-align="center" align="center" label="操作" width="150">
        <template v-slot="{ row }">
          <el-button :disabled="row.auditFlag" type="text" icon="el-icon-s-check" @click="checkUserRisk(row)">审核</el-button>

          <el-dropdown>
              <span class="el-dropdown-link dropdown-btn" :style="{ '--color': themeColor }">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-view" @click.native="$refs.userAppealListRef.initUserAppealList(row.riskRecordId)">
                申诉记录
              </el-dropdown-item>
              <el-dropdown-item :disabled="row.auditFlag" icon="el-icon-refresh-right" @click.native="openUserRiskOptDialogHandle(row)">
                解除风控
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格分页插件 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="searchUserRiskForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchUserRiskForm.limit"
      :total="totalNum"
      :disabled="dataLoad"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 用户申诉记录列表弹出框 -->
    <user-appeal-list ref="userAppealListRef" />

    <!-- 用户申诉审核弹出框   -->
    <audit-risk :type-enums="typeEnums" :status-enums="statusEnums" @refresh="getUserRiskList" ref="auditRiskRef" />

    <!-- 用户风控操作弹出框 -->
    <user-risk ref="userRiskDialog" @close-dialog="closeUserRiskDialogHandle" />
  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import UserAppealList from "@/components/user/appeal/list/list.vue";
  import AuditRisk from "@/components/risk/audit";
  import UserRisk from "@/components/risk/risk-user";

  export default {
    layout: 'admin',
    name: "admin-risk-user",
    components: { AuditRisk, RightToolBar, UserAppealList, UserRisk },
    data() {
      return {
        // 用户风控记录列表
        userRiskList: [],
        // 用户风控记录检索是否显示
        searchUserRiskVisible: true,
        // 用户风控记录检索表单对象
        searchUserRiskForm: {
          // 用户主键
          userId: '',
          // 用户风控类型
          riskType: '',
          // 用户风控状态
          status: '',
          // 创建时间（开始）
          startCreateTime: '',
          // 创建时间（结束）
          endCreateTime: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
        },
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前风控记录总数量
        totalNum: 0,
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 被风控得用户列表
        userList: [],
        // 用户风控类型枚举列表
        typeEnums: [],
        // 用户风控状态枚举列表
        statusEnums: [],
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,

      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
    },
    filters: {
      /**
       * 用户风控类型格式化输出
       * @param {number} value     用户风控类型值
       * @param {Array}  typeEnums 用户风控类型枚举列表
       * @returns {string} 用户风控类型名称
       */
      parseRiskType(value, typeEnums) {
        for (let typeEnum of typeEnums) {
          if (typeEnum.value === value) {
            return typeEnum.name;
          }
        }
        return '未知';
      },
      /**
       * 用户风控状态格式化输出
       * @param {number} value     用户风控状态值
       * @param {Array} statusEnums 用户风控状态枚举列表
       */
      parseStatus(value, statusEnums) {
        for (let statsEnum of statusEnums) {
          if (statsEnum.value === value) {
            return statsEnum.name;
          }
        }
        return '未知'
      }
    },
    created() {
      if (process.client) {
        this.initPage()
          .then(() => {})
          .catch(() => {})
          .finally(() => {
            // 表格数据加载结束
            this.dataLoad = false;
          })
      }
    },
    methods: {
      /**
       * 初始化页面方法
       */
      async initPage() {
        // 开始表格数据加载
        this.dataLoad = true;
        /*
          初始化页面枚举数据
         */
        const enumsRes = await this.$axios.$get('/sys/user-risk/enums');
        const enumsData = enumsRes.data;
        this.userList = enumsData.userList;
        this.typeEnums = enumsData.typeEnumList;
        this.statusEnums = enumsData.statusEnumList;
        let searchForm = {
          page: 1,
          limit: 10
        }
        const userRiskListRes = await this.$axios.$post('/sys/user-risk/page/list', searchForm);
        const page = userRiskListRes.data;
        this.userRiskList = page.list;
        this.totalNum = page.totalNum;
        // 假设所有风控记录是‘可’审核的
        for (let userRisk of this.userRiskList) {
          this.$set(userRisk, 'auditFlag', false);
        }
      },
      /**
       * 获取用户风控记录列表方法
       */
      getUserRiskList() {
        let searchUserRiskForm = this.searchUserRiskForm;
        if (searchUserRiskForm.startCreateTime && searchUserRiskForm.endCreateTime
          && searchUserRiskForm.startCreateTime > searchUserRiskForm.endCreateTime) {
          this.notify('', '温馨提示', '检索条件，开始日期不能大于结束日期')
          return;
        }
        // 开始表格数据加载
        this.dataLoad = true;
        this.$axios.$post('/sys/user-risk/page/list', searchUserRiskForm)
          .then(({ data:page }) => {
            this.userRiskList = page.list;
            this.totalNum = page.totalNum;
            // 假设所有风控记录是‘可’审核的
            for (let userRisk of this.userRiskList) {
              this.$set(userRisk, 'auditFlag', false);
            }
          })
          .catch(() => {})
          .finally(() => {
            // 表格数据加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 检索风控记录事件
       */
      searchUserRiskHandle() {
        this.searchUserRiskForm.page = 1;

        this.getUserRiskList();
      },
      /**
       * 表格每页显示数量变化事件
       * @param val 最新值
       */
      sizeChangeHandle (val) {
        this.searchUserRiskForm.page = 1;
        this.searchUserRiskForm.limit = val
        this.getUserRiskList()
      },
      /**
       * 表格页码切换事件
       * @param val 最新值
       */
      currentChangeHandle (val) {
        let searchUserRiskForm = this.searchUserRiskForm
        if (searchUserRiskForm.page === val) {
          return
        }
        searchUserRiskForm.page = val
        this.getUserRiskList()
      },
      /**
       * 重置用户风控记录检索表单对象事件
       */
      resetSearchUserRiskFormHandle() {
        let searchUserRiskForm = this.searchUserRiskForm;
        searchUserRiskForm.userId = '';
        searchUserRiskForm.riskType = '';
        searchUserRiskForm.status = '';
        searchUserRiskForm.startCreateTime = '';
        searchUserRiskForm.endCreateTime = '';
        searchUserRiskForm.page = 1;
      },
      /**
       * 校验用户风控记录是否可审核
       * @param {Object} userRisk 用户风控记录对象
       */
      checkUserRisk(userRisk) {
        // 按钮禁用
        this.buttonLoad = true;
        this.$axios.$get('/sys/user-risk/check', { params: { riskRecordId: userRisk.riskRecordId }})
          .then(() => {
            this.$refs.auditRiskRef.initAuditRiskDialog(userRisk, true);
          })
          .catch(err => {
            if (err.code === 409) {
              // 风控‘审核’按钮禁用
              userRisk.auditFlag = true;
            }
          })
          .finally(() => {
            // 按钮回复可使用
            this.buttonLoad = false;
          })
      },
      /**
       * 打开用户申诉审核弹出框事件
       * 查看用户风控数据
       * @param {Object} userRisk 用户风控记录对象
       */
      openAuditRiskDialogHandle(userRisk) {
        this.$refs.auditRiskRef.initAuditRiskDialog(userRisk, false);
      },
      /**
       * 打开用户风控操作弹出框事件
       * @param {Object} userRisk 用户风控记录对象
       */
      openUserRiskOptDialogHandle(userRisk) {
        // 按钮禁用
        this.buttonLoad = true;
        this.$axios.$get('/sys/user-risk/check', { params: { riskRecordId: userRisk.riskRecordId }})
          .then(() => {
            this.$refs.userRiskDialog.initRemoveUserRiskDialog(userRisk, false);
          })
          .catch(err => {
            if (err.code === 409) {
              // 风控‘审核’按钮禁用
              userRisk.auditFlag = true;
            }
          })
          .finally(() => {
            // 按钮回复可使用
            this.buttonLoad = false;
          })
      },
      /**
       * 打开用户风控操作弹出框事件
       * @param {boolean} refresh 表格数据是否刷新[true-刷新 false-不刷新]
       */
      closeUserRiskDialogHandle(refresh) {
        if (refresh) {
          this.getUserRiskList();
        }
      },
    }
  }
</script>

<style scoped>
  .risk-page .m-tool {
    height: 30px;
    margin-bottom: 7px;
  }
  .risk-page .riskReason {
    white-space: nowrap;
    cursor: pointer;
  }
  .risk-page .riskReason:hover {
    /*通过预先定义一个变量，防止编译器报错*/
    --color: black;
    color: var(--color);
  }
  .risk-page .paging {
    text-align: right;
    margin: 7px;
  }
  .risk-page .dropdown-btn {
    font-size: 12px;
    margin-left: 7px;
    /*通过预先定义一个变量，防止编译器报错*/
    --color: black;
    color: var(--color);
  }
  .date-picker {
    width: 45%;
  }
</style>
